import { message, Space, Popconfirm, Tag, Card, Descriptions } from "antd";
import { ButtonGroup, Button } from "@douyinfe/semi-ui";
import { IconPlusCircle, IconUserAdd } from "@douyinfe/semi-icons";
import { useModel } from "umi";
import { useReactive } from "ahooks";

const OrganizationDatabase = () => {
    const { remoteData } = useModel("global");
    const { selectedGateway, selectedOrganization, updateSelectedOrganization, loadOrganizationServices, changeServiceStatus, organizationServices } = useModel("gateway.info");

    let schemas = selectedOrganization.databases?.map((item) => item.schemas).join(",") || "";

    const state = useReactive({
        submitLoading: false,
        scripts: [],
    });

    const createDatabaseUser = async () => {
        state.submitLoading = true;
        let res = await remoteData({
            object: "multi-organization-gateway",
            serviceUrl: selectedGateway.url,
            serviceName: "/organization/singleDatabaseMode/createDatabaseUser",
            params: { uuid: selectedOrganization.uuid },
        });
        if (res) {
            message.success("成功创建组织数据库用户信息");
            updateSelectedOrganization(res);
        }
        state.submitLoading = false;
    };

    const createDatabase = async () => {
        state.submitLoading = true;
        let params = {
            uuid: selectedOrganization.uuid,
            dbName: "org_" + selectedOrganization?.uuid,
            dbScma: [],
        };
        let res = await remoteData({
            object: "multi-organization-gateway",
            serviceUrl: selectedGateway.url,
            serviceName: "/organization/singleDatabaseMode/createDatabase",
            params,
        });

        if (res) {
            message.success("成功创建组织物理数据库");
            updateSelectedOrganization(res);
        }
        state.submitLoading = false;
    };

    const createAllinoneService = async () => {
        if (schemas.length === 0) return message.warning("组织数据库没有数据模式信息, 不能创建数据服务");
        state.submitLoading = true;
        let res = await remoteData({
            object: "multi-organization-gateway",
            serviceUrl: selectedGateway.url,
            serviceName: "/organization/singleDatabaseMode/createAllinoneGraphqlService",
            organizationUuid: selectedOrganization.uuid,
            params: { organizationUuid: selectedOrganization.uuid },
        });
        if (res) {
            changeServiceStatus(res.serviceUuid, true);
            message.success("成功创建组织数据服务");
            loadOrganizationServices();
        }
        state.submitLoading = false;
    };

    let extraActions = [];

    if (!(selectedOrganization.databaseUser && selectedOrganization.databasePassword)) {
        extraActions.push(
            <Button key={1} loading={state.submitLoading} icon={<IconUserAdd />} onClick={createDatabaseUser}>
                创建数据库用户
            </Button>
        );
    }

    if (selectedOrganization.databaseDeployMode === "single" && selectedOrganization.databaseUser && selectedOrganization.databasePassword && !selectedOrganization.databaseDbName) {
        extraActions.push(
            <Popconfirm key={2} title="确认要创建该组织的物理数据库吗?" okButtonProps={{ loading: state.submitLoading }} placement="topRight" onConfirm={createDatabase}>
                <Button icon={<IconPlusCircle />}>创建数据库</Button>
            </Popconfirm>
        );
    }

    if (
        selectedOrganization.databaseUser &&
        selectedOrganization.databasePassword &&
        selectedOrganization.databaseDbName &&
        schemas.length > 0 &&
        organizationServices.findIndex((item) => item.serviceName === "allinone_graphql_service") === -1
    ) {
        extraActions.push(
            <Popconfirm key={3} title="确认要创建数据服务吗?" placement="topRight" onConfirm={createAllinoneService}>
                <Button icon={<IconPlusCircle />}>创建数据服务</Button>
            </Popconfirm>
        );
    }

    return (
        <div>
            <Card bordered={true} hoverable title="数据库信息" size="small" style={{ marginBottom: 10 }} bodyStyle={{ padding: 10 }} extra={<ButtonGroup>{extraActions}</ButtonGroup>}>
                <Descriptions style={{ padding: "0 10px" }} column={3} size="small" labelStyle={{ width: 100 }}>
                    <Descriptions.Item label="用户名">{selectedOrganization.databaseUser}</Descriptions.Item>
                    <Descriptions.Item label="用户密码">{selectedOrganization.databasePassword}</Descriptions.Item>
                </Descriptions>

                {selectedOrganization.databaseDeployMode === "single" && (
                    <Descriptions style={{ padding: "0 10px" }} column={3} size="small" labelStyle={{ width: 100 }}>
                        <Descriptions.Item label="数据库名" span={3}>
                            {selectedOrganization.databaseDbName}
                        </Descriptions.Item>
                        <Descriptions.Item label="数据库模式" span={3}>
                            <Space wrap>{selectedOrganization.databases?.map((item) => item.schemas.map((_item) => <Tag>{_item}</Tag>))}</Space>
                        </Descriptions.Item>
                    </Descriptions>
                )}
            </Card>

            {state.scripts.length > 0 && (
                <Card
                    bordered={true}
                    hoverable
                    title={<span style={{ color: "red" }}>数据库结构更新出错，下面是待更新的数据库SQL：</span>}
                    size="small"
                    style={{ marginBottom: 10 }}
                    bodyStyle={{ padding: 0 }}
                >
                    <pre>{state.scripts.map((item) => item)}</pre>
                </Card>
            )}
        </div>
    );
};

export default OrganizationDatabase;
